package com.liesheng.haylou.ui.setting.vm;

import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.liesheng.daemonlib.LogUtil;
import com.liesheng.haylou.R;
import com.liesheng.haylou.base.BaseVm;
import com.liesheng.haylou.bluetooth.BleManager;
import com.liesheng.haylou.bluetooth.BleUUIDs;
import com.liesheng.haylou.ui.setting.SetttingEqActivity;
import com.liesheng.haylou.utils.DeviceUtil;
import com.liesheng.haylou.utils.sp.SpKey;
import com.liesheng.haylou.utils.sp.SpUtil;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Date:2019/11/27
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 */
public class SetttingEqVm extends BaseVm<SetttingEqActivity> {

    private String customize_value;
    private String customize_flag;
    private final int CUSTOMIZE_POSITION = 1;//自定义选项的位置

    private int selectPosition;

    private String address;

    public SetttingEqVm(SetttingEqActivity mActivity) {
        super(mActivity);
        selectPosition = SpUtil.getInt(SpKey.EQ_POSITION, 2);
    }

    private final int deltDur = 10;
    private final int num = 25;

    public void initBezierPointX() {
        int[] xs = new int[5];
        xs[0] = getCenterX(mActivity.mBinding.seekBar1);
        xs[1] = getCenterX(mActivity.mBinding.seekBar2);
        xs[2] = getCenterX(mActivity.mBinding.seekBar3);
        xs[3] = getCenterX(mActivity.mBinding.seekBar4);
        xs[4] = getCenterX(mActivity.mBinding.seekBar5);
        mActivity.mBinding.bezierView.initPointsX(xs);
    }

    //均衡器跳到指定位置
    public void scrollToProgress(final SeekBar seek_bar, final int target) {
        final int progess = target * 100;
        int curPro = seek_bar.getProgress();
        final int deltP = (progess - curPro) / num;
        //添加一个滑动的过渡动画
        final Subscription subscription = Observable
                .interval(0, deltDur, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .take(num + 1)
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        int p = seek_bar.getProgress() + deltP;
                        if ((deltP > 0 && p >= progess) || (deltP < 0 && p <= progess)) {
                            seek_bar.setProgress(progess);
                            updateBezierView();
                            return;
                        }
                        seek_bar.setProgress(p);
                    }
                });

        mActivity.addSubscription(subscription);
    }
    //刷新曲线 write2Device : 是否写入ble
    boolean write2Device = false;

    public void updateBezierView() {
        float[] ys = new float[5];
        ys[0] = (float) mActivity.mBinding.seekBar1.getProgress() / mActivity.mBinding.seekBar1.getMax();
        ys[1] = (float) mActivity.mBinding.seekBar2.getProgress() / mActivity.mBinding.seekBar2.getMax();
        ys[2] = (float) mActivity.mBinding.seekBar3.getProgress() / mActivity.mBinding.seekBar3.getMax();
        ys[3] = (float) mActivity.mBinding.seekBar4.getProgress() / mActivity.mBinding.seekBar4.getMax();
        ys[4] = (float) mActivity.mBinding.seekBar5.getProgress() / mActivity.mBinding.seekBar5.getMax();

        mActivity.mBinding.bezierView.updateBezierView(ys);

        if (write2Device) {
            String value = "ff" + getHex(ys[0]) + getHex(ys[1]) + getHex(ys[2]) + getHex(ys[3]) + getHex(ys[4]);
            if (!value.equals(lastValue))
                lastValue = value;
                BleManager.getInstance().write(address, BleUUIDs.CHAR_EQ, value);
        }

    }

    private String lastValue;

    private String getHex(float progress) {
        int v = (int) (progress * 100);
        if (v < 10)
            return "0" + v;
        return "" + v;
    }

    //加载调节EQ的选项
    public void addEqItem() {

        String[] eqItems = mActivity.getResources().getStringArray(R.array.eq_items);
        String[] eqItems_value = mActivity.getResources().getStringArray(R.array.eq_items_values);

        for (int i = 0; i < eqItems.length; i++) {
            TextView textView = new TextView(mActivity);
            textView.setText(eqItems[i].split("-")[1]);
            textView.setTextColor(mActivity.getResources().getColor(R.color.color_C4C4C6));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
            textView.setLayoutParams(lp);
            textView.setTag(eqItems_value[i]);
            if (i == CUSTOMIZE_POSITION) {
                customize_flag = eqItems_value[i].split("-")[0];
                customize_value = SpUtil.getString(SpKey.EQ_CUSTOMIZE_VALUE, eqItems_value[i]);
                textView.setTag(customize_value);
            }
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
            textView.setPadding(DeviceUtil.dip2px(20), DeviceUtil.dip2px(20), DeviceUtil.dip2px(20), 0);

            final int finalI = i;
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    write2Device = false;
                    scroll2Position(finalI);
                }
            });

            mActivity.mBinding.layoutItem.addView(textView);
        }

        scroll2Position(selectPosition);

    }

    //刷新自定义,记录自定义的值
    public void updateCustomize() {
        int p1 = 100 * mActivity.mBinding.seekBar1.getProgress() / mActivity.mBinding.seekBar1.getMax();
        int p2 = 100 * mActivity.mBinding.seekBar2.getProgress() / mActivity.mBinding.seekBar2.getMax();
        int p3 = 100 * mActivity.mBinding.seekBar3.getProgress() / mActivity.mBinding.seekBar3.getMax();
        int p4 = 100 * mActivity.mBinding.seekBar4.getProgress() / mActivity.mBinding.seekBar4.getMax();
        int p5 = 100 * mActivity.mBinding.seekBar5.getProgress() / mActivity.mBinding.seekBar5.getMax();

        customize_value = customize_flag + "-" + p1 + "-" + p2 + "-" + p3 + "-" + p4 + "-" + p5;

        mActivity.mBinding.layoutItem.getChildAt(CUSTOMIZE_POSITION).setTag(customize_value);
        if (selectPosition != CUSTOMIZE_POSITION) {
            scroll2Position(CUSTOMIZE_POSITION);
        }
    }

    //滑动到最近的view
    public void scrollToNearView() {
        LinearLayout layout = mActivity.mBinding.layoutItem;
        int[] xx = new int[layout.getChildCount()];
        for (int i = 0; i < layout.getChildCount(); i++) {
            View view = layout.getChildAt(i);
            xx[i] = getCenterX(view);
        }

        scroll2Position(getMin(xx));
    }


    //scrollView滑动到指定位置
    private void scroll2Position(final int position) {
        final View view = mActivity.mBinding.layoutItem.getChildAt(position);

        for (int i = 0; i < mActivity.mBinding.layoutItem.getChildCount(); i++) {
            View child = mActivity.mBinding.layoutItem.getChildAt(i);
            if (child instanceof TextView) {
                if (i == position) {
                    ((TextView) child).setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                    ((TextView) child).setTextColor(mActivity.getResources().getColor(R.color.white));
                } else {
                    ((TextView) child).setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                    ((TextView) child).setTextColor(mActivity.getResources().getColor(R.color.color_C4C4C6));
                }
            }
        }
        mActivity.mBinding.horizontalScrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mActivity.mBinding.horizontalScrollView.smoothScrollBy(getCenterX(view) - getCenterX(mActivity.mBinding.horizontalScrollView), 0);
                selectPosition = position;
            }
        }, 80);


        String value = (String) view.getTag();
        String[] vs = value.split("-");
        scrollToProgress(mActivity.mBinding.seekBar1, Integer.valueOf(vs[1]));
        scrollToProgress(mActivity.mBinding.seekBar2, Integer.valueOf(vs[2]));
        scrollToProgress(mActivity.mBinding.seekBar3, Integer.valueOf(vs[3]));
        scrollToProgress(mActivity.mBinding.seekBar4, Integer.valueOf(vs[4]));
        scrollToProgress(mActivity.mBinding.seekBar5, Integer.valueOf(vs[5]));

        BleManager.getInstance().write(address, BleUUIDs.CHAR_EQ, value.replaceAll("-",""));
        SpUtil.put(SpKey.EQ_POSITION, position);
        LogUtil.d(getClass().getSimpleName(),"selectPosition = "+position);

    }

    private int getCenterX(View view) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int x = location[0];

        return x + view.getWidth() / 2;
    }

    private int getMin(int[] xx) {
        int center = getCenterX(mActivity.mBinding.horizontalScrollView);
        int min = 0;
        for (int i = 0; i < xx.length; i++) {
            if (Math.abs(xx[i] - center) < Math.abs(xx[min] - center)) {
                min = i;
            }
        }
        return min;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SpUtil.put(SpKey.EQ_CUSTOMIZE_VALUE, customize_value);
        SpUtil.put(SpKey.EQ_POSITION, selectPosition);
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setWrite2Device(boolean write2Device) {
        this.write2Device = write2Device;
    }
}
